//
//  shiplistViewController.m
//  
//
//  Created by turing on 15/11/24.
//
//

#import "shiplistViewController.h"
#import "shipListCell.h"
#import "shipDetailViewController.h"
#import "RealTimeLocViewController.h"
#import "Order.h"

@interface shiplistViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIButton *currentButton;
@property(nonatomic, strong)UIButton *hisButton;
@property(nonatomic, strong)UILabel *chooseLine;
@property(nonatomic, assign)BOOL oneOrTwo;
@property(nonatomic, strong)NSMutableArray *sourceArr;// 数据源数组


@end

@implementation shiplistViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.sourceArr = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navtitle.text = @"货单";
    self.leftButton.hidden = YES;
    [self initWithView];
    self.oneOrTwo = NO;
    [self loadData];
}

#pragma mark UITabelViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSDictionary *dic = [self.sourceArr objectAtIndex:indexPath.row];
    Order *order = [self.sourceArr objectAtIndex:indexPath.row];
    
    NSString * indentifer = @"shipList";
    
    shipListCell *cell = (shipListCell *)[tableView dequeueReusableCellWithIdentifier:indentifer];
    if (!cell)
    {
        cell=[[NSBundle mainBundle] loadNibNamed:@"shipList" owner:self options:nil][0];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.number.text = @"货单号:";
    cell.number.textAlignment = 2;
    cell.address.text = @"地址:";
    cell.address.textAlignment = 2;
    cell.medium.text = @"介质:";
    cell.medium.textAlignment = 2;
    cell.weight.text = @"重量:";
    cell.weight.textAlignment = 2;
    if (self.oneOrTwo) {
        cell.price.text = @"订单状态:";
        cell.price.textAlignment = 2;
        cell.order.text = @"";
        UILabel *emptyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, cell.price.frame.origin.y + cell.price.frame.size.height, kUIScreenWidth, 1)];
        emptyLabel.backgroundColor = [UIColor HexStrWithColor:@"888888"];
        [cell.contentView addSubview:emptyLabel];
        cell.vehicle.text = @"备注:";
        cell.vehicle.textAlignment = 2;
        cell.chact.hidden = YES;
        cell.vehicle.text = @"";
    } else{
        cell.price.text = @"成交价:";
        cell.price.textAlignment = 2;
        cell.order.text = @"货单订单:";
        cell.order.textAlignment = 2;
        cell.vehicle.text = @"承运车辆:";
        cell.vehicle.textAlignment = 2;
        cell.chact.hidden = NO;
        cell.remarkLabel.text = @"";
        cell.remarkInfoLabel.text = @"";
    }
    
   // 货单号下面的线
    cell.line.backgroundColor = [UIColor HexStrWithColor:@"ADADAD"];
    cell.chact.layer.cornerRadius = 3;
    cell.chact.layer.masksToBounds = YES;
    cell.chact.backgroundColor = [UIColor HexStrWithColor:@"EA7500"];
    cell.chact.titleLabel.font = [UIFont systemFontOfSize:13];
    [cell.chact setTitle:@"    实时位置" forState:UIControlStateNormal];
    [cell.chact setTintColor:[UIColor whiteColor]];
    cell.chact.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [cell.chact addTarget:self action:@selector(chectButtonAction:) forControlEvents:UIControlEventTouchDown];
    
    cell.w_number.text = order.orderNo;//@"4";[NSString stringWithFormat:@"%ld", order.orderId];//[dic objectForKey:@"orderNo"];//货单号;
    cell.w_number.textAlignment = 0;
    cell.w_address.text = order.startAddressName;//[dic objectForKey:@"startAddressName"];//出发地;
    cell.w_address.textAlignment = 0;
    [cell.w_address sizeToFit];
    cell.addImage = [[UIImageView alloc] initWithFrame:CGRectMake(cell.w_address.frame.origin.x + cell.w_address.frame.size.width + 10, cell.address.frame.origin.y - 7, 15, 15)];
    cell.addImage.image = [UIImage imageNamed:@"jt_xl"];
    [cell.contentView addSubview:cell.addImage];
    cell.toaddress.frame = CGRectMake(cell.addImage.frame.origin.x + cell.addImage.frame.size.width , cell.addImage.frame.origin.y, 100, 20);
    cell.toaddress.text = order.endAddressName;//[dic objectForKey:@"endAddressName"];//目的地
    [cell.toaddress sizeToFit];
    cell.toaddress.textAlignment = 0;
    cell.w_medium.text = order.mediumName;//[dic objectForKey:@"mediumName"];//货物介质
    cell.w_medium.textAlignment = 0;
    cell.w_weight.text = order.weight;//[dic objectForKey:@"weight"];//货物重量
    cell.w_weight.textAlignment = 0;
    
    // 历史货单
    if (self.oneOrTwo) {
        cell.w_price.text = order.orderStatus;//[dic objectForKey:@"orderStatus"];//@"8000元";
//        if ([[dic objectForKey:@"note"] isEqualToString:@""] || [dic objectForKey:@"note"] == NULL) {
//            cell.remarkInfoLabel.text = [dic objectForKey:@"note"];
//        }
        cell.w_price.textAlignment = 0;
        cell.w_vehicle.text = @"黑A88888";
        cell.w_vehicle.textAlignment = 0;
        cell.w_order.text = @"";
        cell.w_vehicle.text = @"";
        cell.remarkInfoLabel.text = order.note;
    } else{
        // 当前货单
        cell.w_price.text = order.expectFreight;//成交价
        cell.w_price.textAlignment = 0;
        cell.w_order.text = order.orderStatus;//货单状态
        cell.w_order.textAlignment = 0;
        cell.w_vehicle.text = order.licensePlate;//车辆牌号
        cell.w_vehicle.textAlignment = 0;
    }
    
    if (self.oneOrTwo) {
        // 备注下的空白(历史货单)
        cell.lineLabel.frame = CGRectMake(-1, cell.remarkLabel.frame.origin.y + cell.remarkLabel.frame.size.height, kUIScreenWidth + 2, 10);
        cell.lineLabel.backgroundColor = [UIColor HexStrWithColor:@"FCFCFC"];
        cell.lineLabel.layer.borderColor = [UIColor HexStrWithColor:@"ADADAD"].CGColor;
    }else{
        // 备注下的空白（当前货单）
        cell.lineLabel.frame = CGRectMake(-1, cell.vehicle.frame.origin.y + cell.vehicle.frame.size.height, kUIScreenWidth + 2, 10);
        cell.lineLabel.backgroundColor = [UIColor HexStrWithColor:@"FCFCFC"];
        cell.lineLabel.layer.borderColor = [UIColor HexStrWithColor:@"ADADAD"].CGColor;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = [self.sourceArr objectAtIndex:indexPath.row];
    
    NSString *imei = @"xuguo";
    NSString *resu = [UtilsHelper MD5:imei];
    NSLog(@"resu === %@====%@", resu, kIdentifierString);
    [DataController getOrderDetail:[NSNumber numberWithInt:4]
                            userId:[NSNumber numberWithInt:9]
                          userType:@"2"
                              imei:kIdentifierString
                         withBlock:^(NSDictionary *result) {
                             NSLog(@"result == %@", result);
                             if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                 NSLog(@"数据来了");
                                 NSDictionary *data = [result objectForKey:@"data"];
                                 Order *order = [MTLJSONAdapter modelOfClass:[Order class] fromJSONDictionary:data error:nil];
                                 shipDetailViewController *shipDetailVC = [[shipDetailViewController alloc] initWithGoodsList:order];
                                 [self.navigationController pushViewController:shipDetailVC animated:YES];
                             } else if ([[result objectForKey:@"resCode"] isEqualToString:@"2"]){
                                 NSLog(@"成功踢掉前一个用户，你赢了");
                             }
                         }];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240;
}

- (void)chectButtonAction:(UIButton *)button{
    RealTimeLocViewController *realTimeLocationVC = [[RealTimeLocViewController alloc] init];
    [self.navigationController pushViewController:realTimeLocationVC animated:YES];
}

/**
 *  当前货单按钮
 *
 *  @param button <#button description#>
 */
- (void)currentButtonAction:(UIButton *)button{
    [self.currentButton setTitleColor:[UIColor HexStrWithColor:@"EA0000"] forState:UIControlStateNormal];
    [self.hisButton setTitleColor:[UIColor HexStrWithColor:@"272727"] forState:UIControlStateNormal];
    
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.chooseLine.frame = CGRectMake(0, 39, kUIScreenWidth / 2, 2);
    } completion:^(BOOL finished) {
    }];
    self.oneOrTwo = NO;
    [self.tableView reloadData];
    [self loadData];
}

/**
 *  历史货单按钮
 *
 *  @param button <#button description#>
 */
- (void)hisButtonAction:(UIButton *)button{
    [self.currentButton setTitleColor:[UIColor HexStrWithColor:@"272727"] forState:UIControlStateNormal];
    [self.hisButton setTitleColor:[UIColor HexStrWithColor:@"EA0000"] forState:UIControlStateNormal];
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.chooseLine.frame = CGRectMake(kUIScreenWidth / 2, 39, kUIScreenWidth / 2, 2);
    } completion:^(BOOL finished) {
    }];
    self.oneOrTwo = YES;
//    [self.tableView reloadData];
    [self getHisOrder];
}

- (UIView *)headerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kNavHeight, kUIScreenWidth, 40)];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, 0.5)];
    lineLabel.backgroundColor = [UIColor HexStrWithColor:@"5B5B5B"];
    [view addSubview:lineLabel];
    
    
    self.currentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.currentButton.frame = CGRectMake(0, 0, kUIScreenWidth / 2, 40);
    [self.currentButton setTitle:@"当前货单" forState:UIControlStateNormal];
    [self.currentButton setTitleColor:[UIColor HexStrWithColor:@"EA0000"] forState:UIControlStateNormal];
    [self.currentButton addTarget:self action:@selector(currentButtonAction:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:self.currentButton];
    
    self.hisButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.hisButton.frame = CGRectMake(kUIScreenWidth / 2, 0, kUIScreenWidth / 2, 40);
    [self.hisButton setTitle:@"历史货单" forState:UIControlStateNormal];
    [self.hisButton setTitleColor:[UIColor HexStrWithColor:@"272727"] forState:UIControlStateNormal];
    [self.hisButton addTarget:self action:@selector(hisButtonAction:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:self.hisButton];
    
    UILabel *downLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 39, kUIScreenWidth, 0.5)];
    downLine.backgroundColor = [UIColor HexStrWithColor:@"5B5B5B"];
    [view addSubview:downLine];
    
    self.chooseLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 38, kUIScreenWidth / 2, 2)];
    self.chooseLine.backgroundColor = [UIColor HexStrWithColor:@"EA0000"];
    [view addSubview:self.chooseLine];
    
    return view;
}

- (void)initWithView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight - kNavHeight) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView = [self headerView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
}

/**
 *  获取当前货单列表信息
 */
- (void)loadData{
    [DataController getCurOrder:[NSNumber numberWithInt:9]
                         userId:[NSNumber numberWithInt:9]
                         lastId:[NSNumber numberWithInt:0]
                       userType:@"2"
                           imei:kIdentifierString
                      withBlock:^(NSDictionary *result) {
                          
                          NSLog(@"result == %@", result);
                          if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                              NSDictionary *data = [result objectForKey:@"data"];
                              NSArray *orderList = [data objectForKey:@"orderList"];
                              for (NSDictionary *dic in orderList) {
                                  Order *order = [MTLJSONAdapter modelOfClass:[Order class] fromJSONDictionary:dic error:nil];
                                  [self.sourceArr addObject:order];
                              }
                              [self.tableView reloadData];
                          }else{
                              [self loadData];
                          }
                    }];
}

/**
 *  获取历史货单列表信息
 */
- (void)getHisOrder{
    
    [DataController getHisOrder:[NSNumber numberWithInt:9]
                         userId:[NSNumber numberWithInt:9]
                         lastId:[NSNumber numberWithInt:0]
                       userType:@"2"
                           imei:kIdentifierString
                      withBlock:^(NSDictionary *result) {
                          
                          if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                              NSDictionary *data = [result objectForKey:@"data"];
                              NSArray *orderList = [data objectForKey:@"orderList"];
                              [self.sourceArr removeAllObjects];
                              for (NSDictionary *dic in orderList) {
                                  Order *order = [MTLJSONAdapter modelOfClass:[Order class] fromJSONDictionary:dic error:nil];
                                  [self.sourceArr addObject:order];
                              }
                              [self.tableView reloadData];
                          }else{
                              [self loadData];
                          }

                          /*
                          NSDictionary *data = [result objectForKey:@"data"];
                          if (data != nil && ![data isEqual:@""]) {
//                              [self.sourceArr removeAllObjects];
                              self.sourceArr = [data objectForKey:@"orderList"];
                              [self.tableView reloadData];
                              return ;
                          } else{
                              [self getHisOrder];
                          }
                           */
                      }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigationf

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
